package com.cole.gx095.controller;


import com.cole.gx095.Repository.*;
import com.cole.gx095.domain.*;
import com.cole.gx095.service.ExhouseService;
import com.cole.gx095.service.SaleConService;
import com.cole.gx095.controller.utils.CommonRep;
import com.cole.gx095.controller.utils.RedisUtil;
import com.cole.gx095.controller.utils.TimeUtils;
import com.cole.gx095.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/saleCon")
@CrossOrigin
@Transactional
public class saleConController {
    @Autowired
    ExwarehouseRepository exhouseRepository;
    @Autowired
    ExhouseService exhouseService;
    @Autowired
    SaleConService saleConService;
    @Autowired
    SalebillRepository salebillRepository;
    @Autowired
    SaleBillgoodsRepository saleBillgoodsRepository;
    @Autowired
    SalecontractRepository salecontractRepository;
    @Autowired
    SaleGroupRepository saleGroupRepository;
    @Autowired
    AttachRepository attachRepository;
    @Autowired
    StockgoodsRepository stockgoodsRepository;


    @GetMapping("/List")
    CommonRep List(Integer currentPage, Integer pageSize){
        Page<Salecontract> page1 = salecontractRepository.findAll(PageRequest.of(currentPage - 1, pageSize));
        List<SaleGroup> saleGroups = saleGroupRepository.findAllBystatus();//
        Long sumAmount = salecontractRepository.sumAmount();
        return CommonRep.ok()
                .data("page",page1)
                .data("saleContractList",page1.getContent())
                .data("sumPurMoney",sumAmount)
                .data("GroupData",saleGroups);
    }

    @GetMapping("/getById/{id}")
    CommonRep getById(@PathVariable Integer id){
        Salecontract byId = salecontractRepository.getById(id);
        return CommonRep.ok()
                .data("Contract",byId);
    }

    @GetMapping("/getBillById/{id}")
    CommonRep getBillById(@PathVariable Integer id){
        //根据合同id找合同
        Salecontract byId = salecontractRepository.getById(id);
        //找出合同对应的发票商品
        List<SaleBillgoods> allBycontractNum = saleBillgoodsRepository.findAllBycontractNum(byId.getContractNum());
        List<PurBillTableData> purBillTableDataList = new ArrayList<>();
        for (SaleBillgoods saleBillgoods : allBycontractNum) {
            Salebill salebill = salebillRepository.getById(saleBillgoods.getBillId());

            PurBillTableData purBillTableData = new PurBillTableData();
            purBillTableData.setBillNum(salebill.getBillNum());
            purBillTableData.setBillDate(salebill.getBillDate());
            purBillTableData.setBillAccount(salebill.getBillAccount());
            purBillTableData.setAttachCount(salebill.getAttachCount());
            purBillTableData.setUpdateCountbill(salebill.getUpdateCount());

            purBillTableData.setTypeName(saleBillgoods.getTypeName());
            purBillTableData.setGoodsName(saleBillgoods.getGoodsName());
            purBillTableData.setModle(saleBillgoods.getModle());
            purBillTableData.setGoodsAccount(saleBillgoods.getGoodsAccount());
            purBillTableData.setGoodsUnitPrice(saleBillgoods.getGoodsUnitPrice());

            purBillTableData.setGoodsSumPrice(saleBillgoods.getGoodsSumPrice());
            purBillTableData.setUsedAccount(saleBillgoods.getUsedAccount());//无效字段
            purBillTableData.setBillType(salebill.getBillType());
            purBillTableData.setCreateDate(salebill.getCreateDate());
            purBillTableData.setCreateAdminTrueName(salebill.getCreateAdminTrueName());
            purBillTableData.setPurBillgoodsId(saleBillgoods.getId());
            purBillTableData.setPurchasebillId(salebill.getId());
            purBillTableDataList.add(purBillTableData);
        }
        purBillTableDataList.forEach(System.out::println);
        return CommonRep.ok().data("BillTableData",purBillTableDataList);
    }

    @PostMapping("/queryBy")
    CommonRep getById( Integer currentPage,
                        Integer pageSize,
                       PurQuery purQuery){
        Page<Salecontract> allBy = saleConService.findAllBy(purQuery, currentPage, pageSize);
        Double sumPurMoney = 0.0;
        for (Salecontract salecontract : allBy) {
            sumPurMoney += salecontract.getContractAmount();
        }
        return CommonRep.ok()
                .data("page",allBy)
                .data("saleContractList",allBy.getContent())
                .data("sumPurMoney",sumPurMoney);
    }

    @PostMapping("/addcontact")
    CommonRep addcontact(Salecontract salecontract,
                         MultipartFile[] files,
                         String salespersonName){
        Integer attachCount = 0;
        if(files == null){
            return CommonRep.warn("请传入文件");
        }
//        String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        System.out.println("staticPath = " + TimeUtils.staticPath);

        if(salecontractRepository.findoneBycontractNum(salecontract.getContractNum()) != null ){
            return CommonRep.warn("请输入唯一编号");
        }

        salecontract.setBillAmount(0.0);//发票总金额
        salecontract.setBillCount(0);//发票数量
        salecontract.setBillStatus(0);//发票状态 未开票
        salecontract.setAttachCount(attachCount);//附件数
        salecontract.setCreateAdminTrueName(RedisUtil.mget("LoginName"));//创建者
        salecontract.setUpdateCount(0);
        salecontract.setCorrelationRate(0.0);

        SaleGroup bysaleperson = saleGroupRepository.findBysaleperson(salespersonName);
        salecontract.setSalespersonId(bysaleperson.getId());
        salecontract.setSalespersonName(salespersonName);
        Salecontract savecontract = salecontractRepository.save(salecontract);

        for (MultipartFile file : files) {
            File file1 = new File(TimeUtils.staticPath+File.separator+"doc"+File.separator+ TimeUtils.getfileTime()+file.getOriginalFilename());
            try {
                file.transferTo(file1);
                System.out.println("file1.getPath() = " + file1.getPath());
                Attach attach = new Attach();
                attach.setAssociationId(savecontract.getId());//关联Id
                attach.setName(file.getOriginalFilename());
                attach.setType(2);//附件类型 2销售合同
                attach.setUrl(file1.getPath());//此处为绝对路径
                attachRepository.save(attach);
                attachCount++;
            } catch (IOException e) {
                e.printStackTrace();
                return CommonRep.warn("存入失败");
            }
        }
        savecontract.setAttachCount(attachCount);
        salecontractRepository.save(savecontract);
        return CommonRep.ok();
    }

    /**
     * 采购发票新增
     * 表Purchasebill新增
     * 表Purchasebillgood新增 在addbill1
     * 表purchasecontract补充发票数量
     * @param files
     * @param purBillTableData
     * contractNum
     * billNum
     * billDate
     * billType
     * @return
     */
    @PostMapping("/addBill")
    CommonRep addBill(MultipartFile[] files,
                      PurBillTableData purBillTableData,
                      String contractNum){
        Integer attachCount = 0;
        if(files == null){
            return CommonRep.warn("请上传文件");
        }
//        String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        System.out.println("staticPath = " + TimeUtils.staticPath);

        if(salebillRepository.findoneBybillNum(purBillTableData.getBillNum()) != null ){
            return CommonRep.warn("请输入唯一编号");
        }

        Salecontract salecontract = salecontractRepository.findoneBycontractNum(contractNum);
        Salebill salebill = new Salebill();
        salebill.setContractId(salecontract.getId());
        salebill.setContractNum(salecontract.getContractNum());
        salebill.setBillNum(purBillTableData.getBillNum());
        salebill.setBillDate(purBillTableData.getBillDate());
        salebill.setBillType(purBillTableData.getBillType());
        salebill.setAttachCount(attachCount);//此处为0
        salebill.setBillAccount(0.0);//此处为发票总金额 要补充
        salebill.setCreateAdminTrueName(RedisUtil.mget("LoginName"));//创建者
        salebill.setUpdateCount(0);

        salebill.setCorrelationAmount(0.0);
        salebill.setCorrelationRate(0.0);
        salebill.setStatus(0);
        Salebill savebill = salebillRepository.save(salebill);

        for (MultipartFile file : files) {
            File file1 = new File(TimeUtils.staticPath+File.separator+"doc"+File.separator+ TimeUtils.getfileTime()+file.getOriginalFilename());
            try {
                attachCount++;
                file.transferTo(file1);
                System.out.println("file1.getPath() = " + file1.getPath());
                Attach attach = new Attach();
                attach.setAssociationId(savebill.getId());//关联Id
                attach.setName(file.getOriginalFilename());
                attach.setType(3);//附件类型 3销售发票
                attach.setUrl(file1.getPath());//此处为绝对路径
                attachRepository.save(attach);

            } catch (IOException e) {
                e.printStackTrace();
                return CommonRep.warn("存入失败");
            }
        }


        savebill.setAttachCount(attachCount);//此处为实际附件数
        salebillRepository.save(savebill);


        return CommonRep.ok();
    }

    /**
     * 补充addBill
     * 表 PurBillgoods 新增
     * 表 Purchasebill 补充
     *  表purchasecontract补充合同发票总金额 发票状态是否更改
     * @param purBillData
     * billNum;
     * typeName;
     * goodsName;
     * modle;
     * goodsAccount;
     * goodsUnitPrice;
     * goodsSumPrice;
     * @return
     */
    @PostMapping("/addBill1")
    CommonRep addBill1(@RequestBody List<PurBillData> purBillData){
        purBillData.forEach(System.out::println);
        Double BillAccount = 0.0;
        Salebill salebill = salebillRepository.findoneBybillNum(purBillData.get(0).getBillNum());
        Salecontract salecontract = salecontractRepository.getById(salebill.getContractId());
        for (PurBillData purBillDatum : purBillData) {
            //计算发票总金额
            BillAccount += purBillDatum.getGoodsSumPrice();
        }
        if(BillAccount + salebillRepository.sumAmountBycontractNum(salebill.getContractNum()) > salecontract.getContractAmount()){
            salebillRepository.delete(salebill);
            return CommonRep.warn("发票金额大于合同金额");
        }

        for (PurBillData purBillDatum : purBillData) {
            //表 PurBillgoods 新增
            SaleBillgoods saleBillgoods = new SaleBillgoods();
            saleBillgoods.setBillId(salebill.getId());
            saleBillgoods.setContractId(salebill.getContractId());
            saleBillgoods.setContractNum(salebill.getContractNum());
            saleBillgoods.setTypeName(purBillDatum.getTypeName());
            saleBillgoods.setGoodsName(purBillDatum.getGoodsName());
            saleBillgoods.setModle(purBillDatum.getModle());
            saleBillgoods.setGoodsAccount(purBillDatum.getGoodsAccount());
            saleBillgoods.setGoodsUnitPrice(purBillDatum.getGoodsUnitPrice());
            saleBillgoods.setGoodsSumPrice(purBillDatum.getGoodsSumPrice());
            saleBillgoods.setStatus(0);//销售发票商品状态 0正常 1作废
            saleBillgoods.setUsedAccount(0);//使用量
            saleBillgoodsRepository.save(saleBillgoods);
        }
        salebill.setBillAccount(BillAccount); //补充发票金额
        salebillRepository.save(salebill);

        salecontract.setBillCount(salecontract.getBillCount()+1);//发票数量+1
        //补充合同发票总金额 发票状态是否更改
        salecontract.setBillAmount(salecontract.getBillAmount()+BillAccount);
        if(salecontract.getBillAmount() < salecontract.getContractAmount())
            salecontract.setBillStatus(1);
        else if(salecontract.getBillAmount() >= salecontract.getContractAmount())
            salecontract.setBillStatus(2);
        salecontractRepository.save(salecontract);
        return CommonRep.ok();
    }



    @PostMapping("/update")
    CommonRep update(@RequestBody Salecontract salecontract){
        System.out.println("purchasecontract.getId() = " + salecontract.getId());
        salecontract.setUpdateCount(salecontract.getUpdateCount() + 1);
        salecontractRepository.save(salecontract);
        return CommonRep.ok();
    }
    //billNum  BillDate billType
    //purchasebill 表
    @PostMapping("/updateBill")
    CommonRep updateBill(@RequestBody PurBillTableData purBillTableData){
        System.out.println("purBillTableData = " + purBillTableData);
        Salebill salebill = salebillRepository.getById(purBillTableData.getPurchasebillId());
        salebill.setBillNum(purBillTableData.getBillNum());
        salebill.setBillType(purBillTableData.getBillType());
        salebill.setBillDate(purBillTableData.getBillDate());
        salebill.setUpdateCount(salebill.getUpdateCount() + 1);
        salebillRepository.save(salebill);
        return CommonRep.ok();
    }

    //typeName  goodsName modle goodsAccount goodsUnitPrice
    //purBillgoods 表
    @PostMapping("/updateBillDetail")
    CommonRep updateBillDetail(@RequestBody PurBillTableData purBillTableData){
        System.out.println("purBillTableData = " + purBillTableData);
        SaleBillgoods saleBillgoods = saleBillgoodsRepository.getById(purBillTableData.getPurBillgoodsId());
        saleBillgoods.setTypeName(purBillTableData.getTypeName());
        saleBillgoods.setGoodsName(purBillTableData.getGoodsName());
        saleBillgoods.setModle(purBillTableData.getModle());
        saleBillgoods.setGoodsAccount(purBillTableData.getGoodsAccount());
        saleBillgoods.setGoodsUnitPrice(purBillTableData.getGoodsUnitPrice());

        Double amount = saleBillgoods.getGoodsSumPrice();
        saleBillgoods.setGoodsSumPrice(purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice());
        saleBillgoodsRepository.save(saleBillgoods);
        Salebill salebill = salebillRepository.findoneBybillNum(purBillTableData.getBillNum());
        salebill.setBillAccount(salebill.getBillAccount() + purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice() - amount);
        salebillRepository.save(salebill);
        Salecontract salecontract = salecontractRepository.findoneBycontractNum(salebill.getContractNum());
        salecontract.setBillAmount(salecontract.getBillAmount() + purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice() - amount);
        if(purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice() > amount){
            if(salecontract.getBillAmount() < salecontract.getContractAmount())
                salecontract.setBillStatus(1);
            else if(salecontract.getBillAmount() >= salecontract.getContractAmount())
                salecontract.setBillStatus(2);
            salecontractRepository.save(salecontract);
        }
        return CommonRep.ok();
    }

}
